#!/usr/bin/perl 
#===============================================================================
#
#         FILE:  ex.pl
#
#        USAGE:  ./ex.pl  
#
#  DESCRIPTION:  
#
#      OPTIONS:  ---
# REQUIREMENTS:  ---
#         BUGS:  ---
#        NOTES:  ---
#       AUTHOR:  Dr. Fritz Mehner (mn), mehner@fh-swf.de
#      COMPANY:  FH Südwestfalen, Iserlohn
#      VERSION:  1.0
#      CREATED:  06/01/11 17:38:33
#     REVISION:  ---
#===============================================================================

#use strict;
#use warnings;


our %hash = (
		"toplevel-0" => "value",
		"toplevel-1" => 
		{ 
			"sublevel1a"  => "value-1a",
			"sublevel1b"  => "value-1b"
		},
		"toplevel-2" =>
		{
			"sublevel1c" => 
			{
				"value-1c.1" => "replacement-1c.1",
				"value-1c.2" => "replacement-1c.2"
			},
			"sublevel1d" => "value-1d"
		}
		);

hashwalk(\%hash , "\$hash");

my $kkk;
$kkk = $hash{"toplevel-2"};
foreach my $key (keys %$kkk){
	print "TT $$kkk{$key}\n";
}

our $kim="AAA  TT";
print "RETURN=" , getvalue("\$kim") , "\n";
print "RETURN=" , getvalue("\$hash{toplevel-0}") , "\n";
print "RETURN=" , getvalue("\$hash{toplevel-2}{sublevel1d}") , "\n";


# getvaule 
#  description : we can get hash values from string mode.
#  skill : using reference in perl
#
sub getvalue {
	my ($str) = @_;
	my $m;
	my @aa;
	my $aa_cnt=0;
	$str =~ s/\$([^\s\{\$]+)\s*//;
	$m = $1;
	while($str =~ s/\s*\{([^\s\}\$]+)\s*\}\s*//){
		$aa[$aa_cnt] = $1;
		$aa_cnt ++;
	}
	print "cnt =$aa_cnt , m = $m $$m\n";

	if($aa_cnt == 0){
		return $$m;
	}

	my $tt = @aa;
	print "m=" , $m , "\@aa=",@aa , "\n", $tt ,"\n";
	print "KK1=",$$m{$aa[0]} , "\n";
	my $t = $$m{$aa[0]};
	print "KK2=",$t , "\n";
	print "KK3=",$$t{$aa[1]} , "\n";
	print "KK4=",$$m{$aa[0]}{$aa[1]} , "\n";

	$t = $m;
	print "II $i =", ref($t) , "\n";
	for(my $i=0;$i<$aa_cnt;$i++){
		$t = $$t{$aa[$i]};
		print "II $i=", ref($t) , " TT= $t\n";
	}
	return $t;
}

# hashwalk
#  description : traversing the hash tree
#  skill : using reference in perl
#
sub hashwalk
{
	my ($element,$str) = @_;
	print "ELE:$element\n";
	if( ref($element) =~ /HASH/ )
	{
		foreach my $key (keys %$element)
		{
			print $key," => \n";
			hashwalk($$element{$key} , $str . "{" . $key . "}");
		}
	}
	else
	{
		print $element,"\n";
		print "PP " , $str , "=",$element,"\n";
	}
};


